package com.gzw.dms.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.KJ.SelectCityActivity;
import com.gzw.dms.KJ.SelectCustomerActivity;
import com.gzw.dms.KJ.SelectDepartActivity;
import com.gzw.dms.KJ.SelectDiverActivity;
import com.gzw.dms.KJ.SelectJySuppliesActivity;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.AddressInfo;

import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;

import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class UserActivity extends BaseActivity  {
    private Button btn_sign;
    private Context mContext;
    private Toolbar toolbar;
    private LinearLayout layout_siji,layout_gongyingshang,layout_fahuokehu,layout_password;
    private TextView ic_username, ic_password, ic_name, ic_adress,ic_bumen, ic_siji, ic_gongyingshang, ic_fahuokehu;
    private EditText ic_username2, ic_password2, ic_name2;
    private Spinner sp_identity;
    private String  type = "0";
    private UserInfo info;
    private ProgressDialog mProgressDialog;
    private String flag,username,password,realName,driver_province,driver_city,driver_county,fpstste,gys_id,driver_id,fhkh_id,bm_id;
    private AddressInfo addressInfo;
    private Intent mIntent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_register);

    }

    @Override
    protected void initViews() {
        layout_siji = (LinearLayout) findViewById(R.id.layout_siji);
        layout_fahuokehu = (LinearLayout) findViewById(R.id.layout_fahuokehu);
        layout_gongyingshang = (LinearLayout) findViewById(R.id.layout_gongyingshang);
        layout_password = (LinearLayout) findViewById(R.id.layout_password);

        btn_sign = (Button) findViewById(R.id.btn_sign);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ic_username = (TextView) findViewById(R.id.ic_username).findViewById(R.id.tv_left);
        ic_password = (TextView) findViewById(R.id.ic_password).findViewById(R.id.tv_left);
        ic_name = (TextView) findViewById(R.id.ic_name).findViewById(R.id.tv_left);
        ic_bumen = (TextView) findViewById(R.id.ic_bumen);
        ic_adress = (TextView) findViewById(R.id.ic_city);
        ic_siji = (TextView) findViewById(R.id.tv_siji);
        ic_gongyingshang = (TextView) findViewById(R.id.tv_gongyingshang);
        ic_fahuokehu = (TextView) findViewById(R.id.tv_fahuokehu);

        sp_identity = ((Spinner) findViewById(R.id.sp_identity));

        ic_username2 = (EditText) findViewById(R.id.ic_username).findViewById(R.id.et_right);
        ic_password2 = (EditText) findViewById(R.id.ic_password).findViewById(R.id.et_right);
        ic_name2 = (EditText) findViewById(R.id.ic_name).findViewById(R.id.et_right);


    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("用户信息");
        mIntent = getIntent();

        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("1", "司机"));
        ls.add(new SpinnerInfo("2", "供应商"));
        ls.add(new SpinnerInfo("3", "省内项目部"));
        ls.add(new SpinnerInfo("4", "省外项目部"));

        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(mContext, ls);
        sp_identity.setAdapter(Adapter);
        ic_username.setText("用户名:");
        ic_password.setText("密   码:");
        ic_name.setText("真实姓名:");
        addressInfo=new AddressInfo();
        fpstste = (String)mIntent.getExtras().get("fpstste");

        if (fpstste.equals("1")){
            info = (UserInfo) mIntent.getExtras().get(
                    "userinfo");
            setData(info);
        }
    }

    @Override
    protected void initEvents() {

        ic_adress.setOnClickListener(new myOnClick());
        btn_sign.setOnClickListener(new myOnClick());
        ic_adress.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());
        ic_bumen.setOnClickListener(new myOnClick());
        ic_siji.setOnClickListener(new myOnClick());
        ic_fahuokehu.setOnClickListener(new myOnClick());
        ic_gongyingshang.setOnClickListener(new myOnClick());

        sp_identity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
                type = spinnerInfo.getId();
                if (type.equals("1")) {
                    layout_gongyingshang.setVisibility(View.GONE);
                    layout_fahuokehu.setVisibility(View.GONE);
                    layout_siji.setVisibility(View.VISIBLE);

                } else if (type.equals("2")) {
                    layout_gongyingshang.setVisibility(View.VISIBLE);
                    layout_fahuokehu.setVisibility(View.GONE);
                    layout_siji.setVisibility(View.VISIBLE);

                }else if (type.equals("3")) {
                    layout_gongyingshang.setVisibility(View.GONE);
                    layout_fahuokehu.setVisibility(View.VISIBLE);
                    layout_siji.setVisibility(View.GONE);

                }else if (type.equals("4")) {
                    layout_gongyingshang.setVisibility(View.GONE);
                    layout_fahuokehu.setVisibility(View.VISIBLE);
                    layout_siji.setVisibility(View.GONE);

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
    }
    private void setData(UserInfo driverInfo) {
        ic_username2.setText(driverInfo.getUsername());
        ic_username2.setEnabled(false);
        layout_password.setVisibility(View.GONE);
        ic_name2.setText(driverInfo.getRealName());
        ic_bumen.setText(driverInfo.getDepartment_name());
        ic_adress.setText(driverInfo.getUser_address());
        ic_fahuokehu.setText(driverInfo.getCustomer_name());
        ic_gongyingshang.setText(driverInfo.getSuppliers_name());
        ic_siji.setText(driverInfo.getDriver_name());
        btn_sign.setText("修       改");
        driver_province = driverInfo.getUser_province().toString();
        driver_city = driverInfo.getUser_city().toString();
        driver_county = driverInfo.getUser_county_name().toString();
        gys_id = driverInfo.getSuppliers_id();
        driver_id = driverInfo.getDriver_id();
        fhkh_id = driverInfo.getCustomer_id();
        bm_id = driverInfo.getDid();
        type=driverInfo.getFlag();
        int sp = Integer.parseInt(type);
        sp_identity.setSelection(sp-1,true);

        if (type.equals("1")) {
            layout_gongyingshang.setVisibility(View.GONE);
            layout_fahuokehu.setVisibility(View.GONE);
            layout_siji.setVisibility(View.VISIBLE);

        } else if (type.equals("2")) {
            layout_gongyingshang.setVisibility(View.VISIBLE);
            layout_fahuokehu.setVisibility(View.GONE);
            layout_siji.setVisibility(View.VISIBLE);

        }else if (type.equals("3")) {
            layout_gongyingshang.setVisibility(View.GONE);
            layout_fahuokehu.setVisibility(View.VISIBLE);
            layout_siji.setVisibility(View.GONE);

        }else if (type.equals("4")) {
            layout_gongyingshang.setVisibility(View.GONE);
            layout_fahuokehu.setVisibility(View.VISIBLE);
            layout_siji.setVisibility(View.GONE);

        }
    }



    public void SaveHttpClientPost() {
        if (isNull(ic_username2)) {
            T.showShort(mContext, "用户名不能为空");
            return;
        }
        if (fpstste.equals("1")){

        }else {
        if (isNull(ic_password2)) {
            T.showShort(mContext, "密码不能为空");
            return;
        }
        }
        if (isNull(ic_name2)) {
            T.showShort(mContext, "真实姓名不能为空");
            return;
        }
        if (isNull(ic_bumen)) {
            T.showShort(mContext, "所在部门不能为空");
            return;
        }
        if (isNull(ic_adress)) {
            T.showShort(mContext, "所属区域不能为空");
            return;
        }
        username = ic_username2.getText().toString().trim();
        password = ic_password2.getText().toString().trim();
        realName = ic_name2.getText().toString().trim();
        if (info == null)
            info = new UserInfo();
        info.setUsername(username);
        info.setPassword(password);
        info.setRealName(realName);
        info.setDid(bm_id);
        info.setUser_county_name(driver_county);
        info.setUser_city(Integer.parseInt(driver_city));
        info.setUser_province(Integer.parseInt(driver_province));
        info.setUser_address(ic_adress.getText().toString());
        info.setFlag(type);
        SpinnerInfo spinnerInfo=(SpinnerInfo)sp_identity.getSelectedItem();
        type = spinnerInfo.getId();
        flag = type;
        if ("1".equals(type)) {
            if (isNull(ic_siji)) {
                T.showShort(mContext, "绑定司机不能为空");
                return;
            }
            info.setDriver_id(driver_id);
        }

        if ("2".equals(type)) {
            if (isNull(ic_siji)) {
                T.showShort(mContext, "绑定司机不能为空");
                return;
            }
            info.setDriver_id(driver_id);

            if (isNull(ic_gongyingshang)) {
                T.showShort(mContext, "绑定供应商不能为空");
                return;
            }
            info.setSuppliers_id(gys_id);

        }
        if ("3".equals(type)) {
            if (isNull(ic_fahuokehu)) {
                T.showShort(mContext, "绑定发货客户不能为空");
                return;
            }
            info.setCustomer_id(fhkh_id);
        }
        if ("4".equals(type)) {
            if (isNull(ic_fahuokehu)) {
                T.showShort(mContext, "绑定发货客户不能为空");
                return;
            }
            info.setCustomer_id(fhkh_id);

        }

        if (fpstste.equals("1")){
            Change change = new Change();
            change.execute(info);
        }else {
            SignShipOrder signShipOrder = new SignShipOrder();
            signShipOrder.execute(info);
        }
    }

    public class SignShipOrder extends AsyncTask<UserInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(UserInfo... params) {
            Map<String, Object> map = new HashMap<>();
            map.put("userInfo", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appSaveUserInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;
                case R.id.ic_city:
                    Intent mIntent1 = new Intent();
                    mIntent1.putExtra("who", "0");
                    mIntent1.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent1, 2);
                    break;
                case R.id.ic_bumen:
                    Intent mIntent = new Intent();
                    mIntent.putExtra("type", "1");
                     mIntent.setClass(mContext, SelectDepartActivity.class);
                     startActivityForResult(mIntent, 0);
                    break;
                case R.id.tv_siji:
                    Intent mIntent2 = new Intent();
                    mIntent2.putExtra("type", "1");
                    mIntent2.setClass(mContext, SelectDiverActivity.class);
                    startActivityForResult(mIntent2, 1);
                    break;
                case R.id.tv_fahuokehu:
                    Intent mIntent3 = new Intent();
                    mIntent3.putExtra("type", "1");
                    mIntent3.setClass(mContext, SelectCustomerActivity.class);
                    startActivityForResult(mIntent3, 3);
                    break;
                case R.id.tv_gongyingshang:
                    Intent mIntent21 = new Intent();
                    mIntent21.putExtra("type", "1");
                    mIntent21.setClass(mContext, SelectJySuppliesActivity.class);
                    startActivityForResult(mIntent21, 4);
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (resultCode == 0){
            try {
//                ArrayList<String> name1 = data.getStringArrayListExtra("name");
//                String name2 = name1.toString();
//                String name = name2.substring(1,name2.length()-1);
                String name = data.getStringExtra("name");
                bm_id = data.getStringExtra("id");
                ic_bumen.setText(name);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 2){
            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                driver_province = data.getStringExtra("province_id");
                driver_city = data.getStringExtra("city_id");
                String county_id = data.getStringExtra("county_id");
                String str = province+city+county.substring(1,county.length()-1);
                ic_adress.setText(str);
                driver_county = county_id.substring(1,county_id.length()-1);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 1){
            try {
                String name = data.getStringExtra("name");
                driver_id = data.getStringExtra("id");
                ic_siji.setText(name);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 3){
            try {
                String name = data.getStringExtra("name");
                fhkh_id = data.getStringExtra("id");
                ic_fahuokehu.setText(name);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 4){
            try {
                String name = data.getStringExtra("name");
               gys_id= data.getStringExtra("id");
                ic_gongyingshang.setText(name);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }


    }


    public class Change extends AsyncTask<UserInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(UserInfo... params) {
            Map<String, Object> map = new HashMap<>();
            map.put("userInfo", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appUpdateUserInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }


}
